package redis

import (
	"ffmpeg/pkg/setting"
	"github.com/go-redis/redis"
	"github.com/rs/zerolog/log"
)

// 声明一个全局的rdb变量
var rdb *redis.Client

func Setup() {
	// single    cluster    failover
	switch setting.RedisSetting.Mode {
	case "single":
		initRedisClient()
	case "cluster":
		initClusterClient()
	case "failover":
		initFailoverClient()
	}
}

// 普通连接
func initRedisClient() (err error) {
	rdb = redis.NewClient(&redis.Options{
		Addr:     setting.RedisSetting.IpAddr[0],
		Password: setting.RedisSetting.Password, // no password set
		DB:       setting.RedisSetting.DB,       // use default DB
		PoolSize: setting.RedisSetting.PoolSize,
	})

	_, err = rdb.Ping().Result()
	if err != nil {
		log.Error().Msgf("初始化redis数据库出错:%v", err)
		return err
	} else {
		log.Info().Msgf("初始化redis数据库成功!!!")
	}
	return nil
}

// 连接Redis哨兵模式
func initFailoverClient() (err error) {
	rdb := redis.NewFailoverClient(&redis.FailoverOptions{
		MasterName: "master",
		//SentinelAddrs: []string{"x.x.x.x:26379", "xx.xx.xx.xx:26379", "xxx.xxx.xxx.xxx:26379"},
		SentinelAddrs: setting.RedisSetting.IpAddr,
		Password:      setting.RedisSetting.Password, // no password set
		DB:            setting.RedisSetting.DB,       // use default DB
		PoolSize:      setting.RedisSetting.PoolSize,
	})
	_, err = rdb.Ping().Result()
	if err != nil {
		log.Error().Msgf("初始化redis数据库出错:%v", err)
		return err
	} else {
		log.Info().Msgf("初始化redis数据库成功!!!")
	}
	return nil
}

// 连接Redis集群
func initClusterClient() (err error) {
	rdb := redis.NewClusterClient(&redis.ClusterOptions{
		Addrs:    setting.RedisSetting.IpAddr,
		Password: setting.RedisSetting.Password, // no password set
		PoolSize: setting.RedisSetting.PoolSize,
	})
	_, err = rdb.Ping().Result()
	if err != nil {
		log.Error().Msgf("初始化redis数据库出错:%v", err)
		return err
	} else {
		log.Info().Msgf("初始化redis数据库成功!!!")
	}
	return nil
}
